package com.kern.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by caoshi at 11:04 2021/7/30
 */
public class ServletUtil {

    private static final Logger logger = LoggerFactory.getLogger(ServletUtil.class);

    /**
     *  文件下载 设置响应格式
     * @param request
     * @param response
     * @param attachmentName
     * @return
     * @throws IOException
     */
    public static HttpServletResponse setHttpServletResponse(HttpServletRequest request, HttpServletResponse response, String attachmentName) throws IOException {
        String agent = request.getHeader("User-Agent");
        boolean isSafari = agent.contains("Safari") && agent.indexOf("Chrome") < 1;
        if (isMSBrowser(agent)) {
            logger.info("is ie");
            attachmentName = URLEncoder.encode(attachmentName, "UTF-8");
        } else if (isSafari) {
            logger.info("is Safari, index{}", agent.indexOf("Safari"));
            String headerValue = "\"" + encodeURIComponent(attachmentName) + "\";";
            headerValue += " filename*=utf-8''" + encodeURIComponent(attachmentName);
            attachmentName = headerValue;
        } else {
            logger.info("is other");
        }
        logger.info("filename={}", attachmentName);
        if (StringUtils.isNotBlank(attachmentName)) {
            attachmentName = URLEncoder.encode(attachmentName, "utf-8"); // 符合 RFC 6266 标准
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=attachmentName;filename*=utf-8''" + attachmentName);
        response.setHeader("filename", attachmentName);
        return response;
    }

    private static String encodeURIComponent(String value) {
        try {
            return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean isMSBrowser(String userAgent) {
        String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal))
                return true;
        }
        return false;
    }

}
